/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.list.menu;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.vos.datalist.ListHeaderVo;
import cn.easyplatform.type.FieldType;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.HtmlBasedComponent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.*;
import org.zkoss.zul.impl.HeaderElement;

import java.util.Iterator;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SimpleColumnMenu extends Menupopup implements ColumnMenu {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private transient HeaderElement _ref;

    public SimpleColumnMenu(final HtmlBasedComponent cols,
                            final EventListener<Event> eventListener, final boolean isExport,
                            final boolean isPrint) {
        this.setPage(cols.getPage());
        addEventListener(Events.ON_OPEN, new EventListener<OpenEvent>() {
            public void onEvent(OpenEvent event) throws Exception {
                if (event.isOpen()) {
                    if (event.getReference() instanceof A)
                        _ref = (HeaderElement) event.getReference().getParent();
                    else
                        _ref = (HeaderElement) event.getReference();
                    init(cols, eventListener, isExport, isPrint);
                }
            }
        });
    }

    private void init(HtmlBasedComponent cols,
                      EventListener<Event> eventListener, boolean isExport,
                      boolean isPrint) {
        if (getChildren().isEmpty()) {
            // 导出
            Menuitem export = new Menuitem(Labels.getLabel("button.export"));
            export.setAttribute("id", "--exp--");
            export.setIconSclass("z-icon-share z-menu-image");
            export.setParent(this);
            export.addEventListener(Events.ON_CLICK, eventListener);
            export.setVisible(isExport);
            // 打印
            Menuitem print = new Menuitem(Labels.getLabel("button.print"));
            print.setAttribute("id", "--print--");
            print.setIconSclass("z-icon-print z-menu-image");
            print.setParent(this);
            print.addEventListener(Events.ON_CLICK, eventListener);
            print.setVisible(isPrint);
            // 过滤
            Menuitem filter = new Menuitem(Labels.getLabel("datalist.filter"));
            filter.setAttribute("id", "--filter--");
            filter.setIconSclass("z-icon-filter z-menu-image");
            filter.setParent(this);
            filter.addEventListener(Events.ON_CLICK, eventListener);

            // 排序
            /*
             * Menuitem asc = new Menuitem(Messages.get(MZul.GRID_ASC));
             * asc.setSclass("z-listhead-menuascending"); asc.setParent(this);
             * asc.addEventListener(Events.ON_CLICK, eventListener);
             * asc.setAttribute("id", "--asc--");
             *
             * Menuitem des = new Menuitem(Messages.get(MZul.GRID_DESC));
             * des.setSclass("z-listhead-menudescending"); des.setParent(this);
             * des.addEventListener(Events.ON_CLICK, eventListener);
             * des.setAttribute("id", "--dsc--");
             */

            Menuseparator sep = new Menuseparator();
            sep.setParent(this);
            //栏位
            Menu columns = new Menu(Labels.getLabel("datalist.columns"));
            columns.setIconSclass("z-icon-align-justify z-menu-image");
            columns.setParent(this);
            Menupopup mp = new Menupopup();
            mp.setParent(columns);
            // 具体表头
            for (Iterator<?> it = cols.getChildren().iterator(); it.hasNext(); ) {
                final HeaderElement header = (HeaderElement) it.next();
                if (Strings.isBlank(header.getLabel()))
                    continue;
                final Menuitem item = new Menuitem(header.getLabel());
                item.setAutocheck(true);
                item.setCheckmark(true);
                item.setChecked(header.isVisible());
                item.addEventListener(Events.ON_CLICK,
                        new EventListener<Event>() {
                            public void onEvent(Event event) throws Exception {
                                Menupopup pop = (Menupopup) item.getParent();
                                int checked = 0;
                                for (Iterator<?> it = pop.getChildren()
                                        .iterator(); it.hasNext(); ) {
                                    Object obj = it.next();
                                    if (obj instanceof Menuitem
                                            && ((Menuitem) obj).isChecked()) {
                                        checked++;
                                    }
                                }
                                if (checked == 0) {
                                    item.setChecked(true);
                                }
                                header.setVisible(item.isChecked());
                            }
                        });
                item.setParent(mp);
            }
        }
        ListHeaderVo hv = getHeader();
        if (hv != null && !Strings.isBlank(hv.getField())
                && hv.getType() != FieldType.BLOB
                && hv.getType() != FieldType.CLOB
                && hv.getType() != FieldType.OBJECT) {
            getChildren().get(2).setVisible(true);
        } else {
            getChildren().get(2).setVisible(false);
        }
    }

    public ListHeaderVo getHeader() {
        ListHeaderVo hv = null;
        if (_ref instanceof Listheader) {
            Listheader header = (Listheader) _ref;
            hv = header.getValue();
        } else if (_ref instanceof Column) {
            Column header = (Column) _ref;
            hv = header.getValue();
        } else if (_ref instanceof Treecol) {
            Treecol header = (Treecol) _ref;
            hv = (ListHeaderVo) header.getAttribute("value");
        }
        return hv;
    }

    public Object clone() {
        final SimpleColumnMenu clone = (SimpleColumnMenu) super.clone();
        clone._ref = null;
        return clone;
    }
}
